﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Axe.Data.Mapping.Exceptions;
using System.Data.SqlClient;

namespace Axe.Data.Mapping
{
    using Axe.Extensions;
    using System.Data;

    public class SqlDelete : SqlAction
    {
        static readonly Dictionary<Type, string> deleteByPK = new Dictionary<Type, string>();

        public SqlDelete(SqlConnection conn, bool close)
            : base(conn, close)
        {

        }

        public SqlDelete(SqlConnection conn, bool close, SqlTransaction tran, bool commit, bool roolback)
            : base(conn, close,tran,commit,roolback)
        {
            
        }


        #region public bool Delete<T>(object pkValue) where T : class
        /// <summary>
        /// Удаление по первичному ключу
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pkValue"></param>
        /// <returns></returns>
        public bool Delete<T>(object pkValue) where T : class
        {
            Type typeInstance = typeof(T);
            MappingDescription instDescription = MappingDescriptionBuilder.GetDescription(typeInstance);

            if (instDescription == null)
                throw new MappingException(typeInstance, "Could not get mapping description");

            if (instDescription.HasPrimaryKey == false)
                throw new MappingException(typeInstance, "Cannot delete, because entity does not contain primary key");

            lock (deleteByPK)
            {
                if (deleteByPK.ContainsKey(typeInstance) == false)
                {
                    string query = String.Format("DELETE FROM [{0}] WHERE {1} = @PrimaryKeyValue",
                        instDescription.Entity.MappedTableName,
                        instDescription.PrimaryKey.MappedName);

                    deleteByPK.Add(typeInstance, query);
                }
            }

            SqlCommand cmd = this.Connection.CreateCommand();
            cmd.Transaction = this.Transaction;
            cmd.CommandText = deleteByPK[typeInstance];

            string pkParamName = "@PrimaryKeyValue";
            object pkParamValue = pkValue;

            cmd.Parameters.AddWithValue(pkParamName, pkParamValue);

            try
            {
                if (Connection.State == ConnectionState.Closed)
                    Connection.Open();

                int affectedRows = cmd.ExecuteNonQuery();

                if (CommitTransactionOnSuccess && Transaction != null)
                    Transaction.Commit();

                return affectedRows > 0;
            }
            catch (Exception e)
            {
                if (RollbackTransactionOnError)
                    cmd.SafeTransactionRollback();

                throw e;
            }
            finally
            {
                if (CloseConnection)
                    Connection.Close();
            }
        } 
        #endregion

        #region public bool Delete<T>(string propertyName, object propertyValue) where T : class
        public bool Delete<T>(string propertyName, object propertyValue) where T : class
        {
            Type typeInstance = typeof(T);
            MappingDescription instDescription = MappingDescriptionBuilder.GetDescription(typeInstance);

            if (instDescription == null)
                throw new MappingException(typeInstance, "Could not get mapping description");

            SqlCommand cmd = this.Connection.CreateCommand();
            cmd.Transaction = this.Transaction;

            string fieldName = instDescription.MappedFields[propertyName].MappedName;

            cmd.CommandText = String.Format("DELETE FROM [{0}] WHERE {1}=@{1}", instDescription.Entity.MappedTableName, fieldName);
            cmd.Parameters.AddWithValue("@" + fieldName, propertyValue);


            try
            {
                if (Connection.State == ConnectionState.Closed)
                    Connection.Open();

                int affectedRows = cmd.ExecuteNonQuery();

                if (CommitTransactionOnSuccess && Transaction != null)
                    Transaction.Commit();

                return affectedRows > 0;
            }
            catch (Exception e)
            {
                if (RollbackTransactionOnError)
                    cmd.SafeTransactionRollback();

                throw e;
            }
            finally
            {
                if (CloseConnection)
                    Connection.Close();
            }
        } 
        #endregion

        /*
        public bool CascadeDelete<T>(T obj) where T : class
        {

        }*/
    }
}
